package server;

import server.container.Context;
import server.container.Host;
import server.container.Server;
import server.container.Wrapper;

import java.io.InputStream;
import java.net.Socket;
import java.util.Map;

public class RequestProcessor extends Thread {

    private Socket socket;
    private Server server;

    public RequestProcessor(Socket socket, Server server) {
        this.socket = socket;
        this.server = server;
    }

    @Override
    public void run() {
        try{
            InputStream inputStream = socket.getInputStream();

            // 封装Request对象和Response对象
            Request request = new Request(inputStream);
            Response response = new Response(socket.getOutputStream());

            //先匹配到对应context
            String[] str = request.getUrl().split("/");
            String contextRequest = "/" + str[1];
            Host host = server.getService().getEngine().getHost();
            Context context = host.getContextMap().get(contextRequest);
            Map<String, Wrapper> map = context.getMap();
            Wrapper wrapper = map.get("/" + str[2]);
            // 静态资源处理
//            if(servletMap.get(request.getUrl()) == null) {
//                response.outputHtml(request.getUrl());
//            }else{
//                // 动态资源servlet请求
//                HttpServlet httpServlet = servletMap.get(request.getUrl());
//                httpServlet.service(request,response);
//            }
            if(wrapper == null){
                response.outputHtml(request.getUrl());
            }else{
                Servlet servlet = wrapper.getServlet();
                servlet.service(request,response);
            }

            socket.close();

        }catch (Exception e) {
            e.printStackTrace();
        }

    }
}
